<template>
  <view class="SearchBar">
    <view class="searchContainer">
      <view class="searchIcon icon">
        <image src="../../static/img/common/search-grey.png"></image>
      </view>

      <input :disabled="disabled" :value="searchValue" :placeholder="placeholder" placeholder-class="inputPlaceholder" confirm-type="search" @confirm="search"></input>

      <view class="clearIcon icon" @click="clear">
        <image src="../../static/img/common/X.png"></image>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  props: {
    disabled: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: '请输入'
    }
  },
  data() {
    return {
      searchValue: ''
    }
  },
  methods: {
    search(e) {
      this.searchValue = e.detail?.value + ' '
      this.$nextTick(()=> {
        this.searchValue = e.detail?.value?.trim() || ''
        this.$emit('search', this.searchValue)
      })
    },
    clear() {
      if (this.disabled) return
      this.searchValue = ' '
      this.$nextTick(()=> {
        this.searchValue = null
        this.$emit('clear')
      })

    },
    // 清空输入框，父组件可通过$refs获取实例进行调用
    clearValue() {
      this.searchValue = null
    }
  }
}
</script>

<style lang="scss">
.SearchBar {
  padding: 30rpx;

  .searchContainer {
    display: flex;
    height: 64rpx;

    .searchIcon {
      border-radius: 32rpx 0 0 32rpx;

      image {
        width: 28rpx;
        height: 28rpx;
        transform: translateX(2rpx);
      }
    }

    input {
      flex: 1;
      height: 64rpx;
      color: #45474D;
      font-size: 28rpx;
      background-color: #fbfcfe;
      padding-right: 20rpx;
    }

    .clearIcon {
      border-radius: 0 32rpx 32rpx 0;
      border-left: 1rpx solid #E7E8ED;

      image {
        width: 22rpx;
        height: 22rpx;
        transform: translateX(-3rpx);
      }
    }

    .icon {
      width: 68rpx;
      line-height: 64rpx;
      text-align: center;
      background-color: #fbfcfe;
    }
  }
}
</style>
